﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Compiled_Tests.Utils;
using System.Windows.Automation;
using System.Diagnostics;
using Compiled_Tests.RuleBase;
using LEET.CommonInterfaces.TestControls;

namespace Compiled_Tests
{
    public class TestController : BaseController, IController
    {
        RuleBaseController controller;

        public TestController(ITestScript script) : base(script)
        {
            controller = new RuleBaseController(box);
            ActionTaken += controller.ActionTaken;
            RuleBaseRecieved  += controller.RuleBaseRecieved;
            TestFinished += controller.TestFinished;
            TestStarted += controller.TestStarted;
            ProcessRecieved += controller.StartedProcess;
            SignalRecieved += controller.HearSignal;
        }

        private class RuleBaseController
        {
            bool isFirstLine;
            Stack<IRuleBase> stack;
            IBox box;

            public RuleBaseController(IBox box)
            {
                this.stack = new Stack<IRuleBase>();
                this.box = box;
            }
            

            public void TestStarted(ITestScript s)
            {
                if (isFirstLine)
                {
                    stack.Push(new RuleBase.RuleBase());
                }
                isFirstLine = true;
            }

            public void ActionTaken()
            {
                if (isFirstLine)
                {
                    stack.Push(new RuleBase.RuleBase());
                }

                foreach (IRuleBase rb in stack)
                {
                    rb.Run(box);
                }
                isFirstLine = false;
            }

            public void RuleBaseRecieved(IRuleBase rb)
            {
                if (isFirstLine)
                {
                    stack.Push(rb);
                }
                else
                {
                    throw new Exception();
                }
                isFirstLine = false;
            }

            public void TestFinished()
            {
                stack.Pop();
            }

            public void HearSignal(ScriptSignal signal)
            {
                ActionTaken();
            }

            public void StartedProcess(IProcess proc)
            {
                ActionTaken();
            }
        }
        
    }
}
